//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using OpenLS.Core;
using OpenLS.Spreadsheet.Internals;

namespace OpenLS.Spreadsheet
{
    class TableNameManager
    {
        public TableNameManager(Workbook workbook)
        {
            Workbook = workbook;
            tableDefinedNames = new ObservableCollection<TableDefinedName>();
            tableDefinedNames.CollectionChanged += TableDefinedNamesCollectionChanged;

        }

        void TableDefinedNamesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            using (this.Workbook.CreateUndoScope(StringTable.DefineName))
            {
                this.Workbook.AddUndoUnit(new ChangeCollectionUnit<TableDefinedName>(tableDefinedNames,  e));
                if (e.OldItems != null)
                    foreach (DefinedName newName in e.OldItems)
                        Touch(newName.Name);
                if (e.NewItems != null)
                    foreach (DefinedName newName in e.NewItems)
                        Touch(newName.Name);
            }
            Worksheet activeSheet = this.Workbook.View.ActiveSheet as Worksheet;
            if (activeSheet != null && activeSheet.Selection != null)
                activeSheet.Selection.NotifyNameOrLabelChanged();
        }

        private void Touch(string name)
        {
            if (!NameNodes.ContainsKey(name))
                return;
            NameNode nn = NameNodes[name];
                    nn.Touch();
        }


        internal readonly ObservableCollection<TableDefinedName> tableDefinedNames;
  

        public Workbook Workbook
        {
            get; private set;
        }
        internal NameNode GetNameNode(string name)
        {
            if (NameNodes.ContainsKey(name))
                return NameNodes[name];
            var result = new NameNode(name);
            result.UpdateRange(this);
            NameNodes.Add(name, result);
            return result;
        }

        readonly Dictionary<string, NameNode> NameNodes = new Dictionary<string, NameNode>();
    }

    
}
